package com.example.mybatisplus.service.impl;

import com.example.mybatisplus.entity.OiMemRegInfo;
import com.example.mybatisplus.entity.OiMemRegInfoExtend;
import com.example.mybatisplus.entity.PascMembers;
import com.example.mybatisplus.mapper.OiMemRegInfoExtendMapper;
import com.example.mybatisplus.mapper.OiMemRegInfoMapper;
import com.example.mybatisplus.mapper.PascMembersMapper;
import com.example.mybatisplus.service.IOiMemRegInfoExtendService;
import com.example.mybatisplus.service.IOiMemRegInfoService;
import com.example.mybatisplus.service.ISysDateService;
import com.example.mybatisplus.util.DesUtils;
import com.example.mybatisplus.util.HashUtil;
import com.google.common.collect.Lists;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static org.apache.commons.lang3.time.DateFormatUtils.ISO_DATETIME_FORMAT;

/**
 * @author lushunming
 * @date 2019/11/20
 */
@Service
@Log4j2
public class SysDateServiceImpl implements ISysDateService {
    @Resource
    private PascMembersMapper pascMembersMapper;
    @Resource
    private OiMemRegInfoMapper oiMemRegInfoMapper;
    @Resource
    private OiMemRegInfoExtendMapper oiMemRegInfoExtendMapper;
    @Resource
    private IOiMemRegInfoService oiMemRegInfoService;
    @Resource
    private IOiMemRegInfoExtendService oiMemRegInfoExtendService;
    @Resource(name = "oracleJdbcTemplate")
    private JdbcTemplate oracleJdbcTemplate;

    @Override
    public void sysDate() {
        log.info( "--------------------start------------------------------" );
        ExecutorService executorService = Executors.newFixedThreadPool( 8 );

        Calendar calendar = Calendar.getInstance();
        calendar.set( Calendar.YEAR, 2019 );
        calendar.set( Calendar.MONTH, 10 );
        calendar.set( Calendar.DATE, 1 );
        calendar.set( Calendar.HOUR, 0 );
        calendar.set( Calendar.MINUTE, 0 );
        calendar.set( Calendar.SECOND, 0 );
        calendar.set( Calendar.MILLISECOND, 0 );
        Date start = calendar.getTime();
        Date end = DateUtils.addMonths( start, 1 );
        while (start.before( new Date() )) {

            log.info( "-----start:{}", DateFormatUtils.format( start, ISO_DATETIME_FORMAT.getPattern() ) );
            log.info( "-----end:{}", DateFormatUtils.format( end, ISO_DATETIME_FORMAT.getPattern() ) );
            //查询出所有的用户
            StringBuilder sql = new StringBuilder();
            List<java.lang.Object> args = Lists.newArrayList();
            sql.append( "select n.*                                                                                     " );
            sql.append( "       from (select m.*,                                                                       " );
            sql.append( "       row_number() OVER(PARTITION BY username ORDER BY creatordate desc) as row_flg           " );
            sql.append( "       from (                                                                                  " );
            sql.append( "                                                                                               " );
            sql.append( "       select t.*, a.creatordate                                                               " );
            sql.append( "       from PASC_MEMBERS t                                                                     " );
            sql.append( "       left join ASC_PROJECT_HIS2 a                                                            " );
            sql.append( "       on t.guid = a.creatorguid                                                               " );
            sql.append( "       union all                                                                               " );
            sql.append( "       select t.*, a.creatordate                                                               " );
            sql.append( "       from PASC_MEMBERS t                                                                     " );
            sql.append( "       left join ASC_PROJECT a                                                                 " );
            sql.append( "       on t.guid = a.creatorguid                                                               " );

            sql.append( "      ) m) n   " );
            sql.append( "      where n.row_flg = 1      " );
            if (null != start) {
                sql.append( "      and n.datecreated >= ?" );
                args.add( start );
            }
            if (null != end) {
                sql.append( "      and n.datecreated < ?" );
                args.add( end );
            }
            List<PascMembers> users = oracleJdbcTemplate.query( sql.toString(), args.toArray(), BeanPropertyRowMapper.newInstance( PascMembers.class ) );
            log.info( "-------用户信息条数:{}", users.size() );
           /* List<OiMemRegInfo> oiMemRegInfos = Lists.newArrayList();
            List<OiMemRegInfoExtend> oiMemRegInfoExtends = Lists.newArrayList();*/
            for (PascMembers a : users) {

                executorService.submit( new Runnable() {
                    @Override
                    public void run() {
                        try {
                            log.info( "-------data:{}", a.toString() );

                            OiMemRegInfo oiMemRegInfo = new OiMemRegInfo();

                            oiMemRegInfo.setGuid( a.getGuid() );
                            oiMemRegInfo.setAcountId( a.getTelephone());
                            String password = StringUtils.isNotEmpty( a.getPassword() ) ? DesUtils.decrypt( a.getPassword() ) : "";
                            oiMemRegInfo.setPassword( HashUtil.hash( password ) );
                            oiMemRegInfo.setRealName( a.getAliasname() );

                            String userCode = StringUtils.isNotEmpty( a.getUsercode() ) && StringUtils.contains( a.getUsercode(), "=" ) ? DesUtils.decrypt( a.getUsercode() ) : "";
                            oiMemRegInfo.setIdNum( a.getUsercode() );

                            oiMemRegInfo.setBirthday( a.getDatecreated() );
                            oiMemRegInfo.setGender( "" );
                            oiMemRegInfo.setProvince( a.getProvince() );
                            oiMemRegInfo.setCity( a.getCity() );
                            oiMemRegInfo.setArea( a.getArea() );
                            oiMemRegInfo.setAddress( a.getAddress() );
                            oiMemRegInfo.setTelephone( StringUtils.isNotEmpty( a.getMobile() ) && StringUtils.contains( a.getMobile(), "=" ) ? DesUtils.decrypt( a.getMobile() ) : a.getMobile() );
                            oiMemRegInfo.setEmail( a.getEmail() );
                            oiMemRegInfo.setWxOpenId( "" );//TODO
                            oiMemRegInfo.setPostcode( a.getPostcode() );
                            oiMemRegInfo.setAvatar( a.getAvatarurl() );
                            oiMemRegInfo.setNation( a.getMz() );
                            oiMemRegInfo.setPlaceOrigin( a.getJg() );
                            oiMemRegInfo.setQq( a.getQq() );

                            if ("2".equals( a.getSmxx() )) {

                            } else if ("1".equals( a.getSmxx() )) {
                                oiMemRegInfo.setAuthStatus( "2" );
                                oiMemRegInfo.setAuthTime( a.getSmsj() );
                            } else {
                                oiMemRegInfo.setAuthStatus( "0" );
                                oiMemRegInfo.setAuthTime( null );
                            }

                            /**
                             * 0：五期网上办事大厅
                             * 1：APP
                             * 2：交管
                             * 3：微信
                             * 4:交警用户中心
                             * 5:省政务网app
                             */
                            if (StringUtils.equals( "0", a.getXb().toString() )) {
                                oiMemRegInfo.setSource( "PC" );
                            } else if (StringUtils.equals( "1", a.getXb().toString() )) {
                                oiMemRegInfo.setSource( "APP" );

                            } else if (StringUtils.equals( "2", a.getXb().toString() )) {
                                oiMemRegInfo.setSource( "PC" );

                            } else if (StringUtils.equals( "3", a.getXb().toString() )) {
                                oiMemRegInfo.setSource( "WEI" );

                            } else if (StringUtils.equals( "4", a.getXb().toString() )) {
                                oiMemRegInfo.setSource( "SZJJ" );
                            } else if (StringUtils.equals( "5", a.getXb().toString() )) {
                                oiMemRegInfo.setSource( "SZW" );
                            } else {
                                oiMemRegInfo.setSource( "PC" );

                            }

                            oiMemRegInfo.setTrpId( "" );
                            oiMemRegInfo.setRegIp( "" );
                            oiMemRegInfo.setCreateTime( a.getDatecreated() );
                            oiMemRegInfo.setUpdateTime( null );
                            oiMemRegInfo.setUpdater( null );
                            oiMemRegInfo.setAge( null );
                            oiMemRegInfo.setIsdeleted( a.getUseable() == 0L ? new BigDecimal( 1L ) : new BigDecimal( 0L ) );
                            oiMemRegInfo.setSynctime( null );
                            oiMemRegInfo.setSeqNum( null );
                            oiMemRegInfo.setcT( null );
                            oiMemRegInfo.setuT( null );
                            oiMemRegInfo.setSyncId( null );
                            oiMemRegInfo.setZfbId( null );
                            oiMemRegInfo.setUserName(a.getUsername());
                            /*  oiMemRegInfos.add( oiMemRegInfo );*/

                            OiMemRegInfoExtend oiMemRegInfoExtend = new OiMemRegInfoExtend();

                            oiMemRegInfoExtend.setGuid( UUID.randomUUID().toString() );
                            oiMemRegInfoExtend.setUserGuid( a.getGuid() );


                            if ("2".equals( a.getSmxx() )) {
                                oiMemRegInfoExtend.setRealityStatus( "2" );
                                oiMemRegInfoExtend.setRealityTime( a.getSrsj() );
                            } else if ("1".equals( a.getSmxx() )) {

                            } else {
                                oiMemRegInfoExtend.setRealityStatus( "0" );
                                oiMemRegInfoExtend.setRealityTime( null );
                            }

                            oiMemRegInfoExtend.setJurisdiction( "0" );
                            oiMemRegInfoExtend.setUseable( a.getUseable() + "" );
                            oiMemRegInfoExtend.setCreateTime( a.getDatecreated() );
                            oiMemRegInfoExtend.setUpdateTime( null );
                            oiMemRegInfoExtend.setSynctime( null );
                            oiMemRegInfoExtend.setUserType( a.getUsertype().shortValue() );

                            oiMemRegInfoExtend.setIdType( userCode.length() == 15 || userCode.length() == 18 ? new Integer( 0 ).shortValue() : new Integer( 1 ).shortValue() );//TODO
                            oiMemRegInfoExtend.setMaritalStatus( null );
                            oiMemRegInfoExtend.setPolitical( a.getZzmm() );
                            oiMemRegInfoExtend.setEducation( a.getXl() );
                            oiMemRegInfoExtend.setLinkName( a.getLinkname() );
                            /*  oiMemRegInfoExtends.add( oiMemRegInfoExtend );*/
                            log.info( "-------开始插入" );
                            oiMemRegInfoMapper.insert( oiMemRegInfo );
                            oiMemRegInfoExtendMapper.insert( oiMemRegInfoExtend );
                            log.info( "-------insertoiMemRegInfo:{}", oiMemRegInfo.toString() );
                            log.info( "-------insertoiMemRegInfoExtend:{}", oiMemRegInfoExtend.toString() );
                        } catch (Exception e) {
                            e.printStackTrace();
                            log.error( "---------------处理数据出错,数据为" + a.toString(), e );
                            log.error( "---------------处理数据出错;----------------id 为{},", a.getGuid() );
                        }
                    }
                } );
            }

            start = end;
            end = DateUtils.addMonths( start, 1 );
        }
        log.info( "--------------------end------------------------------" );
        log.error( "--------------------end------------------------------" );
    }
}
